// 立即执行初始化
initVideoController();

// 页面加载完成后再次初始化
document.addEventListener('DOMContentLoaded', initVideoController);

// 处理动态加载的视频
const observer = new MutationObserver(() => {
  try {
    initVideoController();
  } catch (error) {
    console.log('视频元素初始化失败:', error);
  }
});

// 等待DOM加载完成后再观察
function observeDOM() {
  if (document.body) {
    observer.observe(document.body, { childList: true, subtree: true });
  } else {
    // 如果body还不存在，等待DOM加载完成
    document.addEventListener('DOMContentLoaded', () => {
      observer.observe(document.body, { childList: true, subtree: true });
    });
  }
}

// 开始观察DOM
observeDOM();

function initVideoController() {
  const videos = document.getElementsByTagName('video');
  const iframes = document.getElementsByTagName('iframe');
  
  console.log('找到视频元素数量:', videos.length);
  console.log('找到 iframe 数量:', iframes.length);
  
  // 处理主页面视频
  if (videos.length > 0) {
    handleVideo(videos[0]);
  }

  // 尝试处理 iframe 中的视频
  for (let iframe of iframes) {
    try {
      // 检查是否是超星慕课的视频播放器
      if (iframe.src.includes('/ananas/modules/video')) {
        // 超星慕课视频处理
        iframe.addEventListener('load', () => {
          try {
            const scriptUrl = chrome.runtime.getURL('inject.js');
            const script = document.createElement('script');
            script.src = scriptUrl;
            iframe.contentWindow.document.head.appendChild(script);

            // 添加消息监听
            if (!chrome.runtime.onMessage.hasListeners()) {
              chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
                try {
                  if (request.type === 'SET_SPEED') {
                    // 通过 postMessage 发送消息到 iframe
                    iframe.contentWindow.postMessage({
                      type: 'SET_SPEED',
                      speed: request.speed
                    }, '*');
                    sendResponse({success: true});
                  }
                } catch (error) {
                  console.log('处理消息失败:', error);
                  sendResponse({success: false, error: error.message});
                }
                return true;
              });
            }
          } catch (e) {
            console.log('注入脚本失败:', e);
          }
        });
      } else {
        // 其他网站的 iframe 视频处理
        iframe.addEventListener('load', () => {
          // 创建并注入跨域通信脚本
          const script = `
            window.addEventListener('message', function(event) {
              const videos = document.getElementsByTagName('video');
              if (videos.length > 0) {
                const video = videos[0];
                
                // 响应速度设置请求
                if (event.data.type === 'SET_SPEED') {
                  video.playbackRate = event.data.speed;
                }
                
                // 响应进度设置请求
                if (event.data.type === 'SET_PROGRESS') {
                  video.currentTime = video.duration * (event.data.progress / 100);
                }
                
                // 响应状态获取请求
                if (event.data.type === 'GET_STATE') {
                  window.parent.postMessage({
                    type: 'VIDEO_STATE',
                    speed: video.playbackRate,
                    progress: (video.currentTime / video.duration) * 100
                  }, '*');
                }
              }
            });
          `;

          // 通过 URL 创建脚本
          const blob = new Blob([script], { type: 'application/javascript' });
          const scriptUrl = URL.createObjectURL(blob);

          // 注入脚本到 iframe
          try {
            iframe.contentWindow.postMessage({
              type: 'INJECT_SCRIPT',
              url: scriptUrl
            }, '*');
          } catch (e) {
            console.log('注入脚本失败:', e);
          }

          // 添加消息监听
          if (!chrome.runtime.onMessage.hasListeners()) {
            chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
              try {
                if (request.type === 'SET_SPEED') {
                  iframe.contentWindow.postMessage({
                    type: 'SET_SPEED',
                    speed: request.speed
                  }, '*');
                  sendResponse({success: true});
                } else if (request.type === 'SET_PROGRESS') {
                  iframe.contentWindow.postMessage({
                    type: 'SET_PROGRESS',
                    progress: request.progress
                  }, '*');
                  sendResponse({success: true});
                } else if (request.type === 'GET_STATE') {
                  iframe.contentWindow.postMessage({
                    type: 'GET_STATE'
                  }, '*');
                  
                  // 监听来自 iframe 的响应
                  window.addEventListener('message', function handler(event) {
                    if (event.data && event.data.type === 'VIDEO_STATE') {
                      sendResponse(event.data);
                      window.removeEventListener('message', handler);
                    }
                  });
                  return true;
                }
              } catch (error) {
                console.log('处理消息失败:', error);
                sendResponse({success: false, error: error.message});
              }
              return true;
            });
          }
        });
      }
    } catch (error) {
      console.log('无法访问 iframe 内容:', error);
    }
  }
}

// 处理单个视频元素
function handleVideo(video) {
  try {
    // 保存原始方法
    const originalPlaybackRate = Object.getOwnPropertyDescriptor(HTMLMediaElement.prototype, 'playbackRate');
    
    // 使用多种方式尝试设置播放速度
    function setVideoSpeed(value) {
      try {
        // 方法1: 直接设置
        video.playbackRate = value;
        
        // 方法2: 使用原始setter
        originalPlaybackRate.set.call(video, value);
        
        // 方法3: 通过video对象的__proto__设置
        Object.getPrototypeOf(video).playbackRate = value;
        
        // 方法4: 注入脚本到video所在的window环境
        const script = document.createElement('script');
        script.textContent = `
          try {
            document.querySelector('video').playbackRate = ${value};
          } catch(e) {
            console.log('注入脚本设置速度失败:', e);
          }
        `;
        (video.ownerDocument || document).head.appendChild(script);
        script.remove();
      } catch (e) {
        console.log('设置视频速度失败:', e);
      }
    }

    // 添加消息监听
    if (!chrome.runtime.onMessage.hasListeners()) {
      chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
        try {
          if (request.type === 'SET_SPEED') {
            setVideoSpeed(request.speed);
            sendResponse({success: true});
          } else if (request.type === 'SET_PROGRESS') {
            video.currentTime = video.duration * (request.progress / 100);
            sendResponse({success: true});
          } else if (request.type === 'GET_STATE') {
            sendResponse({
              speed: video.playbackRate,
              progress: (video.currentTime / video.duration) * 100
            });
          }
        } catch (error) {
          console.log('处理消息失败:', error);
          sendResponse({success: false, error: error.message});
        }
        return true;
      });
    }
  } catch (error) {
    console.log('处理视频失败:', error); 
  }
} 